<?php
  //require('dbconnection.php');
  //session_start();




  //get username and password
$username = isset($_POST['username']) ? $_POST['username']: null;

$password = isset($_POST['passwd']) ? $_POST['passwd']: null;


try{
  // Check that users can't execute commands 
  if ((strstr($username,";")) || (strstr($password,";")))
    throw new Exception("There was semi-colons in the username or password");

  /**
   * I believe (Note Believe) that ypmatch 
   * displays to stdout when a username exists
   * and stderr which is not.
   * This does not seem to be picked up by php.
   */
  $actual = shell_exec("ypmatch ".$username."  passwd");
  if($actual == null)
    throw new Exception("Username does not exist");


  $ypmatcharray = explode(":", $actual);

  $salt = substr($ypmatcharray[1],0,2);

  $attempt = crypt($password,$salt);

 
  if (isset($_POST['username']) && isset($_POST['passwd'])){

    if((strcmp($ypmatcharray[1],$attempt) == 1)){

      throw new Exception("Error password wrong");
    }else{
      session_register('uname');
      //echo $ypmatcharray[1]." ".$attempt;
      $_SESSION['uname'] =$_POST['username'];


      // Name in database login 
      $conn = connectToDB();
      $select ="SELECT * FROM descriptors WHERE user='$username'";

      $result = mysql_query($select); 

      // Had a problem connecting to the database
      if (!$result)
	throw new Exception('Could not execute query');

      if(mysql_num_rows($result)>0){
	include_once('prototype.php');
      }else{
  	include_once('instructions.php');
      }

    }
  }else {
    throw new Exception("Error fields not filled");
  }


}catch(Exception $e){
  //echo $e;
  include_once('errorlogin.php');

}

      
function connectToDB()
{
  //use or create permanent connection
  //a permanent connection means that a check is made 
  //  to see if the connection is already there
  //if so, it is used, otherwise it is created
  //alter username, password and db name when you have created your own
  $db = mysql_pconnect('storo.dcs.gla.ac.uk','kellyjh','0792');
  if ($db)
    //select the database 
    if (mysql_select_db('kellyjh',$db))
      return $db;
  throw new Exception ("Database connection failed, please try later");
}

?>
